package controller

import (
	v1 "api/api/v1/admin"
	"api/internal/model"
	"api/internal/service"
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/gogf/gf/v2/util/grand"
	"github.com/golang-jwt/jwt"
)

type cRegister struct {
}

var (
	Register = cRegister{}
)

// 注册
func (c *cRegister) Retister(ctx context.Context, req *v1.RegisterReq) (res *v1.RegisterRes, err error) {
	var (
		user  *model.UserLoginOutput
		token string
	)
	// 生成 JWT Token
	user = &model.UserLoginOutput{
		Id:           1,
		UserName:     "sujianhui",
		UserNickname: "sujianhui",
		UserPassword: "123456",
		UserSalt:     "123456",
		UserStatus:   2,
		IsAdmin:      0,
		Avatar:       "1",
		DeptId:       0,
	}
	token, err = GenerateToken(user)
	userRes := &v1.RegisterRes{
		Token: token,
	}
	if err != nil {
		return userRes, errors.New("failed to generate token")
	}

	//保存用户信息
	// 检测账号密码是否正确
	err = service.User().Register(ctx, req)
	// if err != nil {
	// 	// 保存登录失败的日志信息
	// 	service.LoginLog().Invoke(ctx, &model.LoginLogInput{
	// 		Status:    0,
	// 		Username:  req.Username,
	// 		Ip:        ip,
	// 		UserAgent: userAgent,
	// 		Msg:       err.Error(),
	// 		Module:    "系统后台",
	// 	})
	// 	return
	// }
	return userRes, nil
}

func (c *cRegister) Say(ctx context.Context, req *v1.SayReq) (res *v1.SayRes, err error) {
	res = &v1.SayRes{
		Token: "123456",
	}
	fmt.Println("hello")
	return
}

// 生成 JWT Token
func GenerateToken(user *model.UserLoginOutput) (string, error) {
	claims := v1.CustomClaims{
		Username: user.UserName,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Add(time.Hour * 24).Unix(), // 过期时间为一天
			Issuer:    "YourAppName",                         // 签发人
			Id:        grand.Digits(32),                      // 随机生成 Token ID
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 使用密钥对 Token 进行签名
	signedToken, err := token.SignedString([]byte("your-secret-key"))
	if err != nil {
		return "", errors.New("failed to generate token")
	}
	return signedToken, nil
}
